#include "StdAfx.h"
#include <algorithm>
#include "PlayerContainer.h"
#include "Player.h"
#include "input/InputManager.h"
#include <sstream>

PlayerContainer::PlayerContainer(std::vector<Packets::PlayerStartInfo> & playerStartInfoList, int localId)
{
	for ( unsigned int i = 0; i < playerStartInfoList.size(); ++i) {
		if (i == localId)
			localPlayer = new Player(playerStartInfoList[i]);
		else
			externalPlayers.push_back(new Player(playerStartInfoList[i]));
	}

	// for debugging add some none owned objs when single player
	if (externalPlayers.empty()) {
		PlayerObj* obj = new PlayerObj(glm::vec3(50.0f, 1.0f, 10.0f), nullptr);
		PlayerObj* obj1 = new PlayerObj(glm::vec3(50.0f, 1.0f, 50.0f), nullptr);
		PlayerObj* obj2 = new PlayerObj(glm::vec3(80.0f, 1.0f, 70.0f), nullptr);
	}
}

PlayerContainer::~PlayerContainer()
{

}

void PlayerContainer::update(float dt) 
{
	localPlayer->draw(dt, true);

	for ( unsigned int i = 0; i < externalPlayers.size(); ++i) {
		externalPlayers[i]->draw(dt, false);
	}
}

std::vector<Player*> PlayerContainer::getEnemyPlayers(Player* player) {

	// TODO for now just return every other player 

	std::vector<Player*> playerList;
	for ( unsigned int i = 0; i < externalPlayers.size(); ++i) {
		if (externalPlayers[i] != player)
			playerList.push_back(externalPlayers[i]);
	}
	if (localPlayer != player) 
		playerList.push_back(localPlayer);

	return playerList;
}

Player* PlayerContainer::getPlayer(int id) 
{
    for ( unsigned int i = 0; i < externalPlayers.size(); ++i ) 
    {
        if ( externalPlayers[i]->hasId(id) ) 
            return externalPlayers[i];
    }
	if (localPlayer->hasId(id))
		return localPlayer;

	std::stringstream ss;
	ss << "External player ID " << id << " has no match\n";
    throw std::runtime_error(ss.str());
}

unsigned int PlayerContainer::nExternalPlayers() { return externalPlayers.size(); }

int PlayerContainer::getLocalPlayerId() { return localPlayer->getId(); }